package com.jeesite.modules.fl.service;

import java.util.Iterator;
import java.util.List;

import javax.validation.ConstraintViolationException;

import com.jeesite.common.lang.StringUtils;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import com.jeesite.modules.fl.dao.DoctorDao;
import com.jeesite.modules.fl.entity.Doctor;


@Service
@Transactional(readOnly=true)
public class DoctorService extends CrudService<DoctorDao,Doctor>{
	
	/**
	 * 获取单条数据
	 * @param doctor
	 * @return
	 */
	@Override
	public Doctor get(Doctor doctor) {
		Doctor entity = super.get(doctor);
		return entity;
	}
	
	public Doctor getByName(String name) {
		List<Doctor> doctors = dao.findByName(name);
		if(doctors.isEmpty()){
			return null;
		}else{
			return doctors.get(0);
		}
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param doctor
	 * @return
	 */
	@Override
	public Page<Doctor> findPage(Page<Doctor> page, Doctor doctor) {
		return super.findPage(page, doctor);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param doctor
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(Doctor doctor) {
		super.save(doctor);
	}

	/**
	 * 更新状态
	 * @param doctor
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(Doctor doctor) {
		super.updateStatus(doctor);
	}
	
	/**
	 * 删除数据
	 * @param doctor
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(Doctor doctor) {
		super.delete(doctor);
	}
	
	@SuppressWarnings("rawtypes")
	@Transactional(readOnly=false)
	public String importData(MultipartFile file, Boolean isUpdateSupport)
    {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        if(file == null)
            throw new ServiceException("请选择导入的数据文件！");
        ExcelImport ei = null;
        
        try
        {
        	ei = new ExcelImport(file, 2, Integer.valueOf(0));
        	List list = ei.getDataList(Doctor.class, new String[0]);
            for(Iterator iterator = list.iterator(); iterator.hasNext();)
            {
            	Doctor doctor = (Doctor)iterator.next();
                try
                {
                	Doctor c = getByName(doctor.getName());
                    if(c == null)
                    {
                        save(doctor);
                        successNum++;
                        successMsg.append((new StringBuilder()).append("<br/>").append(successNum).append("、医师 ").append(doctor.getName()).append(" 导入成功").toString());
                    } else if(isUpdateSupport.booleanValue())
                    {
                    	doctor.setId(c.getId());
                        save(doctor);
                        successNum++;
                        successMsg.append((new StringBuilder()).append("<br/>").append(successNum).append("、医师 ").append(doctor.getName()).append(" 更新成功").toString());
                    } else
                    {
                        failureNum++;
                        failureMsg.append((new StringBuilder()).append("<br/>").append(failureNum).append("、医师 ").append(doctor.getName()).append(" 已存在").toString());
                    }
                }
                catch(Exception e)
                {
                    failureNum++;
                    String msg = (new StringBuilder()).append("<br/>").append(failureNum).append("、医师 ").append(doctor.getName()).append(" 导入失败：").toString();
                    if(e instanceof ConstraintViolationException)
                    {
                        List messageList = ValidatorUtils.extractPropertyAndMessageAsList((ConstraintViolationException)e, ": ");
                        for(Iterator iterator1 = messageList.iterator(); iterator1.hasNext();)
                        {
                            String message = (String)iterator1.next();
                            msg = (new StringBuilder()).append(msg).append(message).append("; ").toString();
                        }

                    } else
                    {
                        msg = (new StringBuilder()).append(msg).append(e.getMessage()).toString();
                    }
                    failureMsg.append(msg);
                    logger.error(msg, e);
                }
            }

        }
        catch(Throwable throwable2)
        {
        	throwable2.printStackTrace();
        }
        finally
        {
            if(ei != null) 
            	ei.close();
        }
        if(failureNum > 0)
        {
            failureMsg.insert(0, (new StringBuilder()).append("很抱歉，导入失败！共 ").append(failureNum).append(" 条数据格式不正确，错误如下：").toString());
            throw new ServiceException(failureMsg.toString());
        } else
        {
            successMsg.insert(0, (new StringBuilder()).append("恭喜您，数据已全部导入成功！共 ").append(successNum).append(" 条，数据如下：").toString());
            return successMsg.toString();
        }
    }

    public void setListEngLang(List<Doctor> doctorList) {
        for (Doctor doctor : doctorList) {
            setEngLang(doctor);
        }
    }

    public void setEngLang(Doctor doctor){
	    if(doctor==null || StringUtils.isBlank(doctor.getId())) return;
        Doctor dbDoctor = get(new Doctor(doctor.getId()));
        if(dbDoctor.getEnName() != null && !dbDoctor.getEnName().isEmpty()){
            doctor.setName(dbDoctor.getEnName());
        }
        if(dbDoctor.getEnDescription() != null && !dbDoctor.getEnDescription().isEmpty()){
            doctor.setDescription(dbDoctor.getEnDescription());
        }
    }
}
